<template>
    <dzs-dialog title="清空日志" width="400px" :isShow="isShow" @close="onCancel" @open="onOpen">
        <div class="calculate-box">
            <div class="calculate-box__left">{{ calculate.left }}</div>
            <div class="calculate-box__method">{{ calculate.method }}</div>
            <div class="calculate-box__right">{{ calculate.right }}</div>
            <div class="calculate-box__equal">=</div>
            <el-input v-model="result" class="calculate-box__input" />
        </div>
        <div class="calculate-box__btn">
            <dzs-button @click="onCancel">取消</dzs-button>
            <dzs-button type="primary" @click="onSubmit">确定</dzs-button>
        </div>
    </dzs-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ElNotification } from 'element-plus';
import { clearLog } from "../api/api"

const props = defineProps({
    isShow: {
        type: Boolean,
        default: false
    }
})


const calculate = ref({
    left: 0,
    right: 0,
    method: '+',
    result: 0
})

const result = ref(0);

const emit = defineEmits(['close', 'onHoldSearch']);

/**生成计算等式*/
const generateEquation = (): { left: number; right: number; method: string; result: number; } => {
    const left = Math.floor(Math.random() * 100) + 1;
    const right = Math.floor(Math.random() * 100) + 1;
    const method = ['+', '-', '*'][Math.floor(Math.random() * 3)];
    const result = eval(`${left}${method}${right}`);
    return {
        left,
        right,
        method,
        result,
    }
}


const onCancel = () => {
    emit('close')
}

const onOpen = () => {
    calculate.value = generateEquation();
}

/**验证*/
const onSubmit = () => {
    if (calculate.value.result != result.value) {
        ElNotification({
            message: "计算错误",
            type: 'error'
        })
        result.value = 0;
        calculate.value = generateEquation();
        return;
    }
    clearLog().then((res) => {
        ElNotification({
            title: '成功',
            message: '清空成功',
            type: 'success'
        })
        onCancel();
        emit("onHoldSearch");
    })
} 
</script>

<style lang="scss" scoped>
.calculate-box {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;

    .calculate-box__left,
    .calculate-box__right,
    .calculate-box__equal,
    .calculate-box__method {
        padding: 5px 20px;
    }


}

.calculate-box__btn {
    display: flex;
    justify-content: flex-end;
}
</style>